# encoding: utf-8
"""
@author:  Zhu Shirui
@file: test_sriver
@time: 2019/11/10 19:42
"""

from selenium import webdriver
from bs4 import BeautifulSoup
import re
import xlwt
import xlrd
import time
from xlutils.copy import copy
import os

path = os.path.dirname(os.path.realpath('__file__'))
file_path = path + '\\oa.xlsx'
print(path)
if os.path.exists(file_path):
    print('  ')
else:
    work_book = xlwt.Workbook(encoding='utf-8')
    sheet = work_book.add_sheet('样品台账')
    work_book.save('oa.xlsx')


def oa_excel(data):
    # 读取信息
    work_book = xlrd.open_workbook(file_path)
    sheet = work_book.sheet_by_index(0)
    rows = sheet.nrows

    # 将xlrd的对象转化为xlwt的对象
    wk = copy(work_book)
    table = wk.get_sheet(0)
    # add applicant
    for i, n in enumerate(data['detail']):
        # 申请人
        table.write(rows, 0, data['applicant'])
        # 项目名称
        table.write(rows, 1, data['project_name'])
        # 申请办事处
        table.write(rows, 2, data['sector'])
        # 申请日期
        table.write(rows, 3, data['date'])
        # 要求完成日期
        if data['detail'][i][2] == '300':
            timeStamp = time.mktime(time.strptime('{}'.format(data['date'].replace('/',' ').replace('/', ' ')), "%Y %m %d")) + 604800
            timeArray = time.localtime(timeStamp)
            otherStyleTime = time.strftime("%Y/%m/%d", timeArray)
            table.write(rows, 4, otherStyleTime)
        else:
            timeStamp = time.mktime(time.strptime('{}'.format(data['date'].replace('/',' ').replace('/', ' ')), "%Y %m %d")) + 1296000
            timeArray = time.localtime(timeStamp)
            otherStyleTime = time.strftime("%Y/%m/%d", timeArray)
            table.write(rows, 4, otherStyleTime)
        # 申请结构
        table.write(rows, 5, data['detail'][i][0])
        # 申请的膜系
        table.write(rows, 6, data['detail'][i][1])
        # 申请的宽度
        table.write(rows, 7, data['detail'][i][2])
        #  申请的高度
        table.write(rows, 8, data['detail'][i][3])
        # 申请的片数
        table.write(rows, 9, data['detail'][i][5])
        # 申请的OA单号
        table.write(rows, 10, data['oa_id'])
        # client_name
        table.write(rows, 11, data['client'])
        # recipent_name
        table.write(rows, 12, data['recipent'][0])
        # recipent_phone
        table.write(rows, 13, data['recipent'][1])
        # recipent_company
        table.write(rows, 14, data['recipent'][2])
        # recipent_address
        table.write(rows, 15, data['recipent'][3])
        rows += 1
        print("数据整理完毕正在写入...................")
        wk.save(file_path)
    print("\n")
    print('{project}项目\t已写入'.format(project=data['project_name']))


loginid = input('请输入账号')
pwd = input('请输入密码')
path = input("请输入chromedriver路径，或将chromedriver拖入此对话框")

# chrome_path = input("请输入chromedriver.exe路径，或将chromedriver拖入此对话框")
options = webdriver.ChromeOptions()
options.add_argument('--headless')
driver = webdriver.Chrome(chrome_options=options, executable_path=path)
driver.get("http://10.0.0.60:8080")

# 登录
driver.find_element_by_name("loginid").send_keys(loginid)
driver.find_element_by_name('userpassword').send_keys(pwd)
driver.find_element_by_id('login').click()

requestid_number = []
# 办结流程请求地址/workflow/request/ViewRequest.jsp?requestid=807471&isovertime=0%27
# 获取 requestid
requestid_url = 'http://10.0.0.60:8080/page/element/compatible/WorkflowTabContentData.jsp?' \
                'tabId=3&ebaseid=8&eid=3&styleid=1390381555293&hpid=21&subCompanyId=163&e71573383469299' \
                '=&pagetype=&fieldids=&fieldvalues=&tabsize=5&e71573383504818='
driver.get(requestid_url)
soup = BeautifulSoup(driver.page_source, 'lxml')
requestid_tag = soup.find_all(name='td', class_="reqdetail")
requestid_regex = r'requestid="(\d+)"'
for i in requestid_tag:
    rqid = re.findall(requestid_regex, str(i))
    requestid_number.append(rqid[0])
with open('requestid.txt', 'a+') as f:
    for i in requestid_number:
        f.write(str(i))
        f.write('\n')
    print("request_id write success\n")

while len(requestid_number) > 0:
    i = requestid_number.pop(-1)
    url = 'http://10.0.0.60:8080/workflow/request/ViewRequest.jsp?requestid={requestid}&isovertime=0'.format(
        requestid=i)
    driver.get(url)
    driver.switch_to.frame('bodyiframe')
    soup = BeautifulSoup(driver.page_source, 'lxml')
    oa_data = {}

    try:
        # OA单号
        oa = soup.find(name='span', id="field12666span")
        oa_id = str(oa)[-24:-7]
        oa_data['oa_id'] = oa_id

        # 申请人
        applicant = soup.find(name="a", onclick="pointerXY(event);")
        # <a href="javaScript:openhrm(16209970);" onclick="pointerXY(event);">罗希</a>
        applicant_regex = '">(.*?)</a>'
        name = re.findall(applicant_regex, str(applicant))
        oa_data['applicant'] = name

        # 项目
        project = soup.find(name="input", id="field12674")
        name_regex = 'value="(.*?)"/>'
        project_name = re.findall(name_regex, str(project))
        oa_data['project_name'] = project_name[0]

        # 申请日期
        # <input type="hidden" id="field12669" name="field12669" value="2019-12-04">
        applicant_date = soup.find(name='input', id="field12669")
        regex_date = 'value="(.*?)"'
        date = re.findall(regex_date, str(applicant_date))
        oa_data['date'] = date[0].replace('-', '/').replace('-', '/')

        # 客户名称
        client = soup.find_all(name='input', id='field12683')
        client_regex = 'value="(.*?)"/>'
        client_name = re.findall(client_regex, str(client))
        oa_data['client'] = client_name[0]

        # 部门
        sector = soup.find_all(name='a', target="_new")
        sector_regex = '_new">(.*?)</a>'
        applicantion_sector = re.findall(sector_regex, str(sector[1]))
        oa_data['sector'] = applicantion_sector[0]

        # 样品结构
        data = soup.find_all(name="tr", _target="datarow")
        coated_regex = 'style="">(.*?)</span>'
        oa_data['detail'] = {}
        for n, i in enumerate(data):
            b = re.findall(coated_regex, str(i))
            oa_data['detail'][n] = b

        address_infor = []
        # recipent
        recipent = soup.find_all(name='input', id="field12742")
        regex_recipent = 'value="(.*?)"/>'
        recipent_name = re.findall(regex_recipent, str(recipent))
        address_infor.append(recipent_name[0])

        # phone
        phone = soup.find_all(name='input', id="field12743")
        regex_phone = 'type="hidden" value="(.*?)"/>'
        phone_number = re.findall(regex_phone, str(phone))
        address_infor.append(phone_number[0])

        # company
        company = soup.find_all(name='input', id="field12745")
        regex_company = 'type="hidden" value="(.*?)"/>'
        company_name = re.findall(regex_company, str(company))
        address_infor.append(company_name[0])

        # receiver_address
        receiver = soup.find_all(name='input', id="field12746")
        regex_address = 'type="hidden" value="(.*?)"/>'
        receiver_address = re.findall(regex_address, str(receiver))
        address_infor.append(receiver_address[0])
        oa_data['recipent'] = address_infor
        oa_excel(oa_data)

    except IndexError:
        print('非样片申请流程。流程申请人:\t', name[0])
        with open('errorRequest.txt', 'a+') as f:
            # write error requestId
            f.write(str(i))
            f.write('\n')

driver.quit()